import axios from 'axios';
import {interface_url , toast} from '../tools'
import route from '../router/index'
import { Indicator } from 'mint-ui';
// const URL_CONTENT_TYPE_JSON = "multipart/form-data;charset=UTF-8";
const URL_CONTENT_TYPE_JSON = "application/json;charset=UTF-8";
const qs = require('qs');
// 环境的切换
axios.defaults.baseURL = interface_url;

// 请求超时时间
axios.defaults.timeout = 10000;

//让ajax携带cookie
axios.defaults.withCredentials=true;
// http request 拦截器
axios.interceptors.request.use(config => {

  // if(localStorage.getItem("token")){
  //   let token = localStorage.getItem("token");
  //   if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
  //     config.headers.common["token"] = localStorage.getItem("token");
  //   }
  // }

  // if(localStorage.getItem("agentId")){
  //   let test = config.data;
  //   if(test){
  //     config.data["agent_id"]=localStorage.getItem("agentId")
  //   }
  // }
  // if(localStorage.getItem("uid")){
  //   let test = config.data;
  //   if(test){
  //     config.data["uid"]=localStorage.getItem("uid")
  //   }
  // }
  // console.log(localStorage.getItem("agentId"))
  return config
}, err => Promise.reject(err));

// http response 拦截器
axios.interceptors.response.use(res => {
  Indicator.close();
  let code = res.data.code;
  if (code == 400){
    console.log("进入")
    toast(res.data.msg)
    // route.push("/");
    // localStorage.removeItem("token")
    // localStorage.removeItem("agentId")
    // localStorage.removeItem("uid")
  }
  if (code == 20302){
    // realNameAlert(function () {
    //   route.push({name:'authentication'})
    // })
  }
  return res
}, error => {
  Indicator.close();
  return Promise.reject(error)
});


/**
 * 获得验证码方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function httpGetCodeService(path, params){
  return new Promise((resolve, reject) =>{
    axios.get(path, {
      params: params
    })
      .then(res => {
        let data = res;
        resolve(data);
      })
      .catch(err => {
        reject(err)
      })
  });
}

/**
 * 上传图片方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function httpUploaderService(path, params){
  return new Promise((resolve, reject) =>{
    axios.post(path, params,{
      headers: {
        'Content-Type': "multipart/form-data"
      }
    })
      .then(res => {
        let data = res.data;
        resolve(data);
      })
      .catch(err => {
        reject(err)
      })
  });
}

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function httpGetService(path, params){
  return new Promise((resolve, reject) =>{
    axios.get(path, {
      params: params
    })
      .then(res => {
        let data = res.data;
        resolve(data);
      })
      .catch(err => {
        reject(err)
      })
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * isToast 是否弹toast  默认true
 * isLoading 是否出现加载loading  默认true
 * contentType 默认 application/json
 */
// export function httpPostService(path, params = {} , isToast = true ,isLoading = true , contentType = URL_CONTENT_TYPE_JSON) {
//   if (isLoading){
//     Indicator.open({
//       text: '加载中...',
//       spinnerType: 'fading-circle'
//     })
//   }
//   return new Promise((resolve, reject) => {
//     axios.post(path, params,{
//       emulateJSON: true,
//       headers: {
//         'Content-Type': contentType,
//       }
//     })
//       .then(res => {
//         let data = res.data.data;
//         let statusCode = res.data.code;
//         let statusText = res.data.msg;
//         if (statusCode == 200)
//         {
//           if (typeof data === 'object' && !(data instanceof Array)){
//             /// 服务器时间
//             let currentTimeMillis = res.data.currentTimeMillis
//             data.currentTimeMillis = currentTimeMillis
//           }
//           resolve(data);
//         }
//
//
//         if (statusCode != 200 &&
//           statusCode != 10000 &&
//           statusCode != 400 &&
//           statusCode != 20302)
//         {
//           if (isToast) {
//             toast(statusText)
//
//           }
//           reject(
//             {code: statusCode , errText: statusText , data :data}
//             )
//         }
//       })
//       .catch(err => {
//         toast("网络错误，请稍后再试")
//       })
//   });
// }

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * isToast 是否弹toast  默认true
 * isLoading 是否出现加载loading  默认true
 * contentType 默认 application/json
 */
export function httpPostService(path, params={}, isToast = true ,isLoading = true , contentType = URL_CONTENT_TYPE_JSON) {
  if (isLoading){
    Indicator.open({
      text: '加载中...',
      spinnerType: 'fading-circle'
    })
  }
  return new Promise((resolve, reject) => {
    axios.post(path,qs.stringify(params),{
      headers: {
        'Content-Type': "application/x-www-form-urlencoded"
      }
    })
      .then(res => {
        console.log(res);
        let data = res.data;
        let statusCode = res.status;
        let statusText = res.statusText;
        if (statusCode == 200)
        {
          // if (typeof data === 'object' && !(data instanceof Array)){
          //   /// 服务器时间
          //   let currentTimeMillis = res.data.currentTimeMillis
          //   data.currentTimeMillis = currentTimeMillis
          // }
          resolve(data);
        }


        if (statusCode != 200 &&
          statusCode != 10000 &&
          statusCode != 400 &&
          statusCode != 20302)
        {
          if (isToast) {
            toast(statusText)

          }
          reject(
            {code: statusCode , errText: statusText , data :data}
          )
        }
      })
      .catch(err => {
        toast("网络错误，请稍后再试")
      })
  });
}
